<template>
  <div class="contractAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave(contractFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item name="1" class="transform-down">
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">新增合同模板信息</span>
        </template>
        <div class="contract-info">
          <el-form
            :model="contractForm"
            ref="contractFormRef"
            :rules="queryRules"
            label-width="100"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="模板类型：" prop="templateType">
                  <el-select
                    ref="refSelect"
                    v-model="contractForm.templateType"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in templateList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="合同模板名称："
                  prop="templateName"
                  label-width="120"
                >
                  <el-input
                    v-model="contractForm.templateName"
                    placeholder="请输入"
                    clearable
                    maxlength="20"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="上传模板：" prop="contractTemplate">
                  <Upload
                    :fileList="contractForm.contractTemplate"
                    :limit="1"
                    limitation="templatelimitation"
                    accept=".doc,.docx"
                    :isFull="true"
                    :isCanDelete="true"
                    :showButton="contractForm.contractTemplate.length == 0"
                    @success="(result) => uploadSuccess(result)"
                    @deleteFile="(result) => uploadRemove(result)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import Upload from "@/components/Upload/index";
import { addContract } from "@/api/information/contract";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  // 合同模板新增组件显隐
  "contractAddShow",
  // 更新合同模板新增组件显隐
  "update:contractAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 合同模板表单引用
const contractFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 下拉框引用
const refSelect = ref();
// 合同模板表单数据模板
const contractFormTemplate = {
  contractTemplate: [],
  templateName: "",
  templateType: null,
};
const data = reactive({
  // 合同模板表单
  contractForm: JSON.parse(JSON.stringify(contractFormTemplate)),
  // 合同模板校验规则
  queryRules: {
    templateName: [
      { required: true, message: "请输入合同模板名称", trigger: "blur" },
    ],
    templateType: [
      { required: true, message: "请选择模板类型", trigger: "change" },
    ],
    contractTemplate: [
      { required: true, message: "请上传模板", trigger: "change" },
    ],
  },
  // 模板列表
  templateList: [],
});
const { contractForm, queryRules, templateList } = toRefs(data);

/**
 * @description: 保存
 * @param {Object} contractFormRef 合同模板表单引用
 */
const handleAddSave = async (contractFormRef) => {
  if (!contractFormRef) return;
  await contractFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          const res = await addContract(contractForm.value);
          if (res.code === 200) {
            emit("update:contractAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            contractForm.value = JSON.parse(
              JSON.stringify(contractFormTemplate)
            );
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  contractFormRef.value.clearValidate('contractTemplate')
  contractForm.value.contractTemplate.push({ ...response, businessType: 3 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  contractForm.value.contractTemplate.splice(index, 1);
}

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("updateEvaluateAddShow", false);
    emit("update:contractAddShow", false);
    contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("updateEvaluateAddShow", false);
        emit("update:contractAddShow", false);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 模板列表
  await getDictsApi("contract_template_type").then((res) => {
    if (res.code === 200) {
      templateList.value = res.data;
    }
  });
}

onMounted(() => {
  getDicts();
  nextTick(() => {
    refSelect.value.focus();
  });
});
</script>
<style lang="scss" scoped>
.contractAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  .contract-info {
    padding: 20px 10px 5px 10px;
    background-color: #fafafa;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }
}
</style>
